package com.newlink.building.common_base.utils


import java.io.File
import java.util.LinkedHashMap

/**
 * @Author: Jake
 * @Date: 2024-06-14
 * @Description:
 */
class LRUCache(private val maxSize: Long) {
    private val cache = LinkedHashMap<File, Long>(16, 0.75f, true)
    private var currentSize = 0L

    @Synchronized
    fun put(file: File) {
        val fileSize = file.length()
        if (file.exists()) {
            cache[file] = file.lastModified()
            currentSize += fileSize
            trimToSize(maxSize)
        }
    }

    @Synchronized
    fun trimToSize(maxSize: Long) {
        val iterator = cache.entries.iterator()
        while (iterator.hasNext()) {
            val entry = iterator.next()
            if (currentSize <= maxSize) break
            val file = entry.key
            val fileSize = file.length()
            if (file.delete()) {
                currentSize -= fileSize
                iterator.remove()
            }
        }
    }

    @Synchronized
    fun get(file: File): Boolean {
        return if (cache.containsKey(file)) {
            cache[file] = file.lastModified()
            true
        } else {
            false
        }
    }
}
